<template>
  <div class="ele-body">
    <a-card :bordered="false">
      <!-- 搜索表单 -->
      <a-form :label-col="{ md: { span: 6 }, sm: { span: 24 } }" :wrapper-col="{ md: { span: 18 }, sm: { span: 24 } }">
        <a-row>
          <a-col :lg="6" :md="12" :sm="24" :xs="24">
            <a-form-item label="编码">
              <!-- 这里不能有code 查询的时候后端page类里有个code 重名了 -->
              <a-input v-model:value.trim="productWhere.keywords" placeholder="请输入编码" allow-clear />
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24" :xs="24">
            <a-form-item label="产品">
              <a-input v-model:value.trim="productWhere.name" placeholder="请输入产品" allow-clear />
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24" :xs="24">
            <a-form-item label="规格">
              <a-input v-model:value.trim="productWhere.specification" placeholder="请输入规格" allow-clear />
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24" :xs="24">
            <a-form-item :wrapper-col="{ span: 24 }">
              <em></em>
              <a-space>
                <a-button type="primary" @click="productReload">查询</a-button>
                <a-button @click="productReset">重置</a-button>
              </a-space>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
      <!-- 表格 -->
      <ele-pro-table ref="productTableRef" row-key="id" :columns="columns" :datasource="datasource"
        :scroll="{ x: 1000 }" cacheKey="product">
        <template #toolbar>
          <a-space>
            <a-button type="primary" @click="productOpenEdit()" v-any-permission="['store:product:save']">
              <template #icon>
                <plus-outlined />
              </template>
              <span>添加</span>
            </a-button>
          </a-space>
        </template>
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'action'">
            <a-space>
              <a @click="productOpenEdit(record)" v-any-permission="['store:product:update']">修改</a>
              <a-divider type="vertical" />
              <a-popconfirm title="确定要删除此项吗？" @confirm="productRemove(record)">
                <a class="ele-text-danger" v-any-permission="['store:product:remove']">删除</a>
              </a-popconfirm>
            </a-space>
          </template>
        </template>
      </ele-pro-table>
    </a-card>
    <!-- 产品管理添加、修改弹窗 -->
    <ele-modal :width="460" v-model:visible="productVisible_modal" :confirm-loading="loading"
      :title="productIsUpdate ? '修改产品管理' : '添加产品管理'" position="center" :body-style="{ paddingBottom: '8px' }"
      @ok="productSave" :maskClosable="false">
      <a-form ref="productFormRef" :model="productForm" :rules="productRules"
        :label-col="{ md: { span: 7 }, sm: { span: 24 } }" :wrapper-col="{ md: { span: 17 }, sm: { span: 24 } }">
        <a-row :gutter="16">
          <a-col :md="24" :sm="24" :xs="24">
            <a-form-item label="名称" name="name">
              <a-input allow-clear :maxlength="200" placeholder="请输入名称" v-model:value="productForm.name"
                autocomplete="off" />
            </a-form-item>
          </a-col>
          <a-col :md="24" :sm="24" :xs="24">
            <a-form-item label="编码" name="code">
              <a-input allow-clear :maxlength="200" placeholder="请输入编码" v-model:value="productForm.code"
                autocomplete="off" />
            </a-form-item>
          </a-col>
          <a-col :md="24" :sm="24" :xs="24">
            <a-form-item label="规格" name="specification">
              <a-input allow-clear :maxlength="200" placeholder="请输入规格" v-model:value="productForm.specification"
                autocomplete="off" />
            </a-form-item>
          </a-col>
          <a-col :md="24" :sm="24" :xs="24">
            <a-form-item label="长度" name="lengths">
              <a-input allow-clear :maxlength="200" placeholder="请输入长度" v-model:value="productForm.lengths"
                autocomplete="off" />
            </a-form-item>
          </a-col>
          <a-col :md="24" :sm="24" :xs="24">
            <a-form-item label="负差" name="negative">
              <a-input allow-clear :maxlength="200" placeholder="请输入负差" v-model:value="productForm.negative"
                autocomplete="off" />
            </a-form-item>
          </a-col>
          <a-col :md="24" :sm="24" :xs="24">
            <a-form-item label="理论质量" name="liweight">
              <a-input allow-clear :maxlength="200" placeholder="请输入理论质量" v-model:value="productForm.liweight"
                autocomplete="off" />
            </a-form-item>
          </a-col>
          <a-col :md="24" :sm="24" :xs="24">
            <a-form-item label="排序" name="ordernum">
              <a-input allow-clear :maxlength="200" placeholder="请输入排序" v-model:value="productForm.ordernum"
                autocomplete="off" />
            </a-form-item>
          </a-col>
          <a-col :md="24" :sm="24" :xs="24">
            <a-form-item label="备注" name="remark">
              <a-textarea :rows="4" :maxlength="200" placeholder="请输入备注" v-model:value="productForm.remark"
                autocomplete="off" />
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </ele-modal>
  </div>
</template>

<script setup>
import { ref, reactive, watch } from 'vue';
import { toDateString } from 'ele-admin-pro';
import useFormData from '@/utils/use-form-data';
import { message } from 'ant-design-vue';
import { TIME_OUT } from '@/config/damon';

import { pageProduct, removeProduct, addProduct, updateProduct } from '@/api/store/product';

// 表格实例
const productTableRef = ref(null);

// 表格列配置
const columns = ref([
  {
    key: 'index',
    width: 48,
    align: 'center',
    fixed: 'left',
    hideInSetting: true,
    customRender: ({ index }) => index + (productTableRef.value?.tableIndex ?? 0)
  },
  {
    title: '名称',
    dataIndex: 'name',
    key: 'name',
    sorter: true
  },
  {
    title: '编码',
    dataIndex: 'code',
    key: 'code',
    sorter: true
  },
  {
    title: '规格',
    dataIndex: 'specification',
    key: 'specification',
    sorter: true
  },
  {
    title: '长度',
    dataIndex: 'lengths',
    key: 'lengths',
    sorter: true
  },
  {
    title: '负差',
    dataIndex: 'negative',
    key: 'negative',
    sorter: true
  },
  {
    title: '理论质量',
    dataIndex: 'liweight',
    key: 'liweight',
    sorter: true
  },
  {
    title: '备注',
    dataIndex: 'remark',
    key: 'remark',
    sorter: true
  },
  {
    title: '排序',
    dataIndex: 'ordernum',
    key: 'ordernum',
    sorter: true
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    key: 'createTime',
    resizable: true,
    width: 150,
    ellipsis: true,
    customRender: ({ text }) => toDateString(text)
  },
  {
    title: '创建人',
    dataIndex: 'createName',
    key: 'createName',
  },
  {
    title: '更新时间',
    dataIndex: 'updateTime',
    key: 'updateTime',
    resizable: true,
    width: 150,
    ellipsis: true,
    customRender: ({ text }) => toDateString(text)
  },
  {
    title: '更新人',
    dataIndex: 'updateName',
    key: 'updateName',
  },
  {
    title: '操作',
    key: 'action',
    width: 200,
    align: 'center',
    fixed: 'right',
    hideInSetting: true
  }
]);

// 表单数据
const { form: productWhere, resetFields } = useFormData({
  username: '',
  sex: undefined
});

// 表格数据源
const datasource = ({ page, limit, where, orders }) => {
  orders.sort = orders.sort == 'updateTime' ? 'update_time' : orders.sort
  orders.sort = orders.sort == 'createTime' ? 'create_time' : orders.sort
  return pageProduct({ ...where, ...orders, page, limit });
};

/* 搜索 */
const productReload = () => {
  productTableRef?.value?.reload({ page: 1, where: productWhere });
};
const productReload2 = () => {
  productTableRef?.value?.reload();
};

let productWhere_timeout = 0
watch(() => productWhere, (val) => {
  clearTimeout(productWhere_timeout)
  productWhere_timeout = setTimeout(() => {
    productReload();
  }, TIME_OUT);
},
  { deep: true }
)

/*  重置 */
const productReset = () => {
  resetFields();
  productReload();
};


// 当前选中数据
const productCurrent = ref(null);

// 弹窗是否打开
const productVisible_modal = ref(false);

// 是否是修改
const productIsUpdate = ref(false);

// 提交状态
const loading = ref(false);

//
const productFormRef = ref(null);

// 表单数据
const { form: productForm, resetFields: productResetFormFields } = useFormData({
  id: undefined,
  customer: '',
  vessel: '',
});

// 表单验证规则
const productRules = reactive({
  name: [
    {
      required: true,
      message: '请输入名称',
      type: 'string',
    }
  ],
});

/* 打开编辑弹窗 */
const productOpenEdit = (record) => {
  productResetFormFields();
  productFormRef.value?.clearValidate();
  productCurrent.value = record ?? {};
  productVisible_modal.value = true;
  Object.assign(productForm, record ?? {});
  productIsUpdate.value = !!record;
  if (!record) {
    productForm.negative = 0
    productForm.lengths = 0
  }
};

/* 保存编辑 */
const productSave = () => {
  if (!productFormRef.value) {
    return;
  }
  productFormRef.value.validate().then(() => {
    loading.value = true;
    const saveOrUpdate = productIsUpdate.value ? updateProduct : addProduct;
    saveOrUpdate(productForm).then((msg) => {
      loading.value = false;
      message.success(msg);
      productVisible_modal.value = false;
      productReload2();
    }).catch((e) => {
      loading.value = false;
      message.error(e.message);
    });
  }).catch(() => {
  });
};

/* 删除单个 */
const productRemove = (record) => {
  const hide = message.loading('请求中..', 0);
  removeProduct(record.id).then((msg) => {
    hide();
    message.success(msg);
    productReload2();
  }).catch((e) => {
    hide();
    message.error(e.message);
  });
};
</script>

<script>
export default {
  name: 'Product'
};
</script>
